/*
 * @Author: your name
 * @Date: 2021-04-30 15:32:30
 * @LastEditTime: 2021-04-30 15:33:47
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \chronic-back-end\common\util.go
 */
package common

import (
	"fmt"
	"os"
	"time"

	"github.com/dgrijalva/jwt-go"
	"golang.org/x/crypto/bcrypt"
)

func Hash(str string) string {
	bytes := []byte(str)
	passwordHash, _ := bcrypt.GenerateFromPassword(bytes, bcrypt.DefaultCost)
	return string(passwordHash)
}

var secretKey = os.Getenv("SECRET_KEY")

type IdClaims struct {
	Id uint `json:"id"`
	jwt.StandardClaims
}

func GenToken(id uint) string {
	jwtToken := jwt.New(jwt.GetSigningMethod("HS256"))
	// Set some claims
	jwtToken.Claims = jwt.MapClaims{
		"id":  id,
		"exp": time.Now().Add(time.Hour * 72).Unix(),
	}
	// Sign and get the complete encoded token as a string
	token, _ := jwtToken.SignedString([]byte(secretKey))
	return token
}

func CheckToken(tokenString string) (uint, error) {
	token, err := jwt.ParseWithClaims(tokenString, &IdClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})

	if token == nil {
		return 0, err
	}

	if claims, ok := token.Claims.(*IdClaims); ok && token.Valid {
		fmt.Printf("%v %v", claims.Id, claims.StandardClaims.ExpiresAt)
		return claims.Id, err
	} else {
		return 0, err
	}
}
